use std::fs::File;
use std::io::Error;
use std::io::Result;
use std::path::PathBuf;

use flate2::read::GzDecoder;
use tar::Archive;

fn main() -> Result<()> {
    let file = File::open("resource/tar/archive.tar.gz")?;
    let mut archive = Archive::new(GzDecoder::new(file));
    let prefix = "archive";

    println!("Extracted the following files:");
    archive
        .entries()?
        .filter_map(|e| e.ok())
        .map(|mut entry| -> Result<PathBuf> {
            let path = entry
                .path()?
                .strip_prefix(prefix)
                .map_err(|_| Error::new(std::io::ErrorKind::Other, "Invalid path"))?
                .to_owned();
            entry.unpack(PathBuf::from("resource/tar/archive").join(&path))?;
            Ok(path)
        })
        .filter_map(|e| e.ok())
        .for_each(|x| println!("> {}", x.display()));

    Ok(())
}
